<?php

namespace common\services\wechat;

use Yii;
use common\extensions\BaseService;
use EasyWeChat\OfficialAccount\Application;

/**
 * Desc 公众号开发
 * * */
class OfficialAccount extends BaseService {
    
    public $app = null;

    /**
     * 初始化公众号
     * @param string $key
     * @return mixed|string
     */
    public function init() {
        $config = [
            'app_id' => '公众号appID',
            'secret' => '公众号appsecret',
            'token' => '公众号token',
            'aes_key' => '' //明文模式下为空
        ];
        $this->app = new Application($config);
    }

    /**
     * 获取公众号openid
     * @param array $params
     * @return mixed|string
     */
    public function getOpenid($params) {
        if ($params['code']) {
            return $this->app->getOauth()->userFromCode($params['code'])->getId();
        }
        unset($params['code']);
        return redirect($this->app->getOauth()->scopes(['snsapi_base'])->redirect(Yii::$app->request->hostInfo.Yii::$app->request->getUrl().'?'.http_build_query($params)));
    }

}
